import {MessageBox, Notification} from 'element-ui'
import store from '@/store'
import router from '@/router'
import manba from 'manba'
import axios from 'axios'
import qs from 'qs'
import * as Utils from '@/utils'
//添加请求拦截器
let toLogin = null;
axios.interceptors.request.use((request) => {
  let token = '';
  if(store.state.app.userInfo) {
    token =  store.state.app.userInfo.token;
  } else  {
    token = window.localStorage.getItem('token');
  }
  if (request.method == 'get') {
    if (typeof request.params != "object") {
      request.params = {};
    }
    request.params.track = Utils.randomTrack();
    request.params.token = token;
  }
  if (typeof request.data != "object") {
    request.data = {};
  }
  request.data.track = Utils.randomTrack();
  /*登录接口不给token*/
  if(!request.data.hasOwnProperty('loginName')) {
    request.data.token = token;
  }
  request.headers["Content-Type"] = "application/x-www-form-urlencoded";
  request.data = qs.stringify(request.data, {allowDots: true});
  return request;
})

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
axios.interceptors.response.use((response) => {
  if (response.data.code == '0001') {
    if(!toLogin) {
      toLogin = MessageBox.alert(response.data.msg, '温馨提示', {
        confirmButtonText: '去登陆',
        callback: action => {
          toLogin = null;
          router.push({name:'Login'})
        }
      });
    }
  }

  if(response.data.code != '0') {
    store.dispatch('addErrorLog',{
      track:response.data.ext.track,
      time: manba().format('yyyy-MM-dd HH:mm:ss')
    })
  }
  return response.data;
}, function (error) {
  Notification.error({
    title: '错误',
    message: `[${error.response.status}]网络请求失败，请重试`,
  });
  return Promise.reject({
    code: "-999",
    msg: `[${error.response.status}]网络请求失败，请重试`,
    data: {
      status: error.response.status,
      statusText: error.response.statusText,
      error
    }
  });
});
